package edu.ynu.se.xiecheng.achitectureclass.Demo1.controller;

import edu.ynu.se.xiecheng.achitectureclass.Demo1.service.AccessTokenService;
import edu.ynu.se.xiecheng.achitectureclass.Demo1.service.DeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/deviceData")
@CrossOrigin(origins = "http://localhost:5173")
public class DeviceDataController {

    @Autowired
    private Map<String, DeviceDataService> serviceMap;

    @Autowired
    private AccessTokenService accessTokenService;

    @PostMapping("/fetchAndSave")
    public String fetchAndSaveData(@RequestParam String dataType, @RequestParam String boxNo) {
        // 获取令牌
        String accessToken = accessTokenService.getToken();
        // 选择具体的设备数据服务
        DeviceDataService service = serviceMap.get(dataType);
        if (service == null) {
            return "未知的数据类型: " + dataType;
        }

        // 使用令牌拉取并保存数据
        service.fetchAndSaveData(accessToken);
        return dataType + " 数据已获取并保存";
    }

    @GetMapping("/history")
    public Object getHistoryData(@RequestParam String dataType) {
        DeviceDataService service = serviceMap.get(dataType);
        if (service == null) {
            return "未知的数据类型: " + dataType;
        }
        return service.getHistoryData(dataType);
    }
}
